package com.chinasoft.mall.framework;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

/**
 * get post 数据请求
 * 
 * @author Administrator
 * 
 */
public class RequestProcessing {
	private static RequestProcessing rp = new RequestProcessing();

	public final static int ERR_NONE = 200;
	public final static int ERR_INVALID_REQUEST = 400;
	public final static int ERR_VALIDATE_ERROR = 401;
	public final static int ERR_REJECT = 403;
	public final static int ERR_BIG_REQUEST = 413;

	public final static int ERR_INVALID_PASSWORD = 422;
	public final static int ERR_NOLOGIN = 423;

	public final static int ERR_SERVER = 500;
	public final static int ERR_SERVER_NOT_AVAILABLE = 503;
	public final static int ERR_OTHERS = 999;
	// 超时
	public final static int ERR_CONNECT_TIMEOUT = 901;

	// 代理设置
	public final static String DEFAULT_PROXY = "http://10.0.0.172";

	public final static String DEFAULT_PROXYPORT = "80";

	private boolean isProxy = false;

	public boolean isProxy() {
		return isProxy;
	}

	public void setProxy(boolean isProxy) {
		this.isProxy = isProxy;
	}

	private RequestProcessing() {
	}

	public static RequestProcessing getInstance() {
		return rp;
	}

	public void cancel() {
		if (urlConnection != null) {
			urlConnection.disconnect();
			urlConnection = null;
		}
	}

	public void Finish() {
		if (urlConnection != null) {
			urlConnection.disconnect();
		}
	}

	/**
	 * 获取网络连接对象
	 * 
	 * @param urlString
	 * @return
	 * @throws Exception
	 */
	public HttpURLConnection getHttpURLConnection(String urlString,
			String reqType, String contentType, String contentLength)
			throws Exception {
		HttpURLConnection connection = null;
		if (isProxy) {
			String urlRelay01 = DEFAULT_PROXY + ":";
			String urlRelay02 = urlRelay01 + DEFAULT_PROXYPORT;
			String tmp01 = urlString.substring(
					urlString.indexOf("/", urlString.indexOf("http://")
							+ "http://".length() + 1), urlString.length());
			String urlRelay = urlRelay02 + tmp01;
			String urlProperty = urlString.substring(
					urlString.indexOf("http://") + "http://".length(),
					urlString.indexOf("/", urlString.indexOf("http://")
							+ "http://".length()));
			URL url = new URL(urlRelay);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			if (reqType.toLowerCase().equals("post")) {
				connection.setDoOutput(true);
			}
			connection.setConnectTimeout(15000);
			connection.setReadTimeout(30000);
			connection.setRequestProperty("X-Online-Host", urlProperty);
		} else {
			try {
				{
					URL url = new URL(urlString);
					connection = (HttpURLConnection) url.openConnection();
					connection.setDoInput(true);
					if (reqType.toLowerCase().equals("post")) {
						connection.setDoOutput(true);
					}
					connection.setConnectTimeout(15000);
					connection.setReadTimeout(30000);
				}
				connection.setRequestMethod(reqType);
				connection.setRequestProperty("Content-Type", contentType);
				connection.setRequestProperty("Charset", "utf-8");

				if (contentLength.length() != 0) {
					connection.setRequestProperty("Content-Length",
							contentLength);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return connection;
	}

	private HttpURLConnection urlConnection = null;

	public String requesturlGBK(String urlString) {
		String result = null;
		try {
			urlConnection = getHttpURLConnection(urlString, "GET",
					"application/json", "");

			urlConnection.setConnectTimeout(20000);

			urlConnection.connect();
			int response = urlConnection.getResponseCode();
			if (response == 200) {
				InputStream in = urlConnection.getInputStream();// .openInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buff = new byte[1024];
				int rc = 0;
				while ((rc = in.read(buff, 0, 1024)) != -1) {
					baos.write(buff, 0, rc);
				}
				byte[] content = baos.toByteArray();
				if (content.length > 0) {
					result = new String(content, "gbk");
				}
				in.close();
				in = null;
				baos.close();
				baos = null;
			} else {
			}
		} catch (IOException e) {
			result = null;
		} catch (Exception e) {
			result = null;
		} finally {
			if (urlConnection != null) {
				urlConnection.disconnect();// .close();
				urlConnection = null;
			}
		}
		return result;
	}

	public String sendPost(String url) throws ClientProtocolException,
			IOException {
		String result = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost get = new HttpPost(url);
		InputStream in = null;
		try {
			HttpResponse response = httpClient.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				entity = new BufferedHttpEntity(entity);
				in = entity.getContent();
				byte[] read = new byte[1024];
				byte[] all = new byte[0];
				int num;
				while ((num = in.read(read)) > 0) {
					byte[] temp = new byte[all.length + num];
					System.arraycopy(all, 0, temp, 0, all.length);
					System.arraycopy(read, 0, temp, all.length, num);
					all = temp;
				}
				result = new String(all, "UTF-8");
			}
		} finally {
			if (in != null)
				in.close();
			get.abort();
		}

		return result;
	}

	public String requesturl(String urlString) throws Exception {

		// HttpClient httpClient = new DefaultHttpClient();
		// HttpPost postMethod = new HttpPost(
		// urlString);
		//
		// try {
		// HttpResponse response = httpClient
		// .execute(postMethod);
		// } catch (ClientProtocolException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		Integer statusCode = -1;
		// Create HttpClient Object
		DefaultHttpClient client = new DefaultHttpClient();
		// Send data by post method in HTTP protocol,use HttpPost instead of
		// PostMethod which was occurred in former version
		HttpPost post = new HttpPost(urlString);
		// Construct a string entity
		// StringEntity entity = new StringEntity(urlString);
		// entity.setContentType("application/json;charset=UTF-8");
		// // Set XML entity
		// post.setEntity(entity);
		// Set content type of request header
		post.setHeader("accept", "application/json");
		post.setHeader("Content-Type", "application/json;charset=UTF-8");
		// Execute request and get the response
		HttpResponse response = client.execute(post);

		// Response Header - StatusLine - status code
		statusCode = response.getStatusLine().getStatusCode();

		if (statusCode != HttpStatus.SC_OK) {
			throw new HttpException("Http Status is error.");
		}
		HttpEntity entityRsp = response.getEntity();
		StringBuffer result = new StringBuffer();
		if (entityRsp != null) {
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					entityRsp.getContent(), HTTP.UTF_8));

			String tempLine = rd.readLine();
			while (tempLine != null) {
				result.append(tempLine);
				tempLine = rd.readLine();
			}

			if (entityRsp != null) {
				entityRsp.consumeContent();
			}
		}
		return result.toString();

	}

	public static InputStream getStringStream(String sInputString) {
		ByteArrayInputStream tInputStringStream = null;
		if (sInputString != null && !sInputString.trim().equals("")) {
			tInputStringStream = new ByteArrayInputStream(
					sInputString.getBytes());
		}
		return tInputStringStream;
	}

	/**
	 * 
	 * @param urlString请求url
	 * @param aData
	 *            json
	 * @return
	 */
	public String postdata(String urlString, String aData) {
		String result = "";
		try {
			byte[] sendcontent = null;
			if (aData != null) {
				sendcontent = aData.getBytes("UTF-8");
			} else {
				return null;
			}
			urlConnection = getHttpURLConnection(urlString, "POST",
					"application/json", Integer.toString(sendcontent.length));

			urlConnection.setConnectTimeout(20000);

			DataOutputStream wr = new DataOutputStream(
					urlConnection.getOutputStream());
			wr.write(sendcontent);
			wr.flush();
			wr.close();
			wr = null;
			int response = urlConnection.getResponseCode();
			if (response == 200) {
				InputStream in = urlConnection.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buff = new byte[1024];
				int rc = 0;
				while ((rc = in.read(buff, 0, 1024)) != -1) {
					baos.write(buff, 0, rc);
				}
				byte[] receivedcontent = baos.toByteArray();
				if (receivedcontent.length > 0) {
					result = new String(receivedcontent, "UTF-8");
				}
				in.close();
				in = null;
				baos.close();
				baos = null;
			} else {
			}
		} catch (IOException e) {
			e.printStackTrace();
			result = null;
		} catch (Exception e) {
			result = null;
		} finally {
			if (urlConnection != null) {
				urlConnection.disconnect();// .close();
				urlConnection = null;
			}
		}
		return result;
	}

}
